package com.xh.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xh.ssm.bean.Project;
import com.xh.ssm.bean.UserinfoProject;
import com.xh.ssm.mapper.ProjectMapper;
import com.xh.ssm.mapper.UserinfoProjectMapper;
import com.xh.ssm.service.ProjectService;
import com.xh.ssm.util.R;
import com.xh.ssm.util.RTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author PangJunjie
 * @Date 2024/1/29/029
 */
@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private UserinfoProjectMapper userinfoProjectMapper;

    public R getPage(int page, int limit, Project project) {
        PageHelper.startPage(page, limit);
        List<Project> list = projectMapper.getList(project);
        PageInfo<Project> pageInfo = new PageInfo<Project>(list);
        return R.page(pageInfo.getTotal(), list);
    }

    public Project getById(int id) {
        return projectMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(Project project) {
        if (project.getId() == null) {
            projectMapper.insertSelective(project);
        } else {
            projectMapper.updateByPrimaryKeySelective(project);
        }
    }

    public void deleteById(int id) {
        List<UserinfoProject> list = userinfoProjectMapper.getListByProjectId(id);
        if (list.isEmpty()) {
            projectMapper.deleteByPrimaryKey(id);
        } else {
            throw new RTException("该项目已被使用，禁止删除！");
        }
    }

    public R getList() {
        return R.ok(projectMapper.getList(new Project()));
    }
}
